<?php
/**
 * Custom global functions
 */

function user_func(): string
{
    return 'hello';
}

/**
 * 获取密钥key
 * @param $serial_number
 * @param $uuid
 * @return string
 */
function mixSecretKey($serial_number, $uuid)
{
    if(!$serial_number || !$uuid) return "";
    $key = $serial_number . ':' . $uuid;
    return 'mixSecretKey:' . sha1($key);
}


function JSON($array) {
    arrayRecursive($array, 'urlencode', true);
    $json = json_encode($array);
    return urldecode($json);
}

function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
    static $recursive_counter = 0;
    if (++$recursive_counter > 1000) {
        die('possible deep recursion attack');
    }
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }

        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter--;
}


/**
 * 去除空格 和 空项
 * @param $arr
 * @return array
 */
function trimItem($arr)
{
    if(empty($arr))
    {
        return [];
    }

    $data = [];
    foreach($arr as $item)
    {
        $data[] = trim($item);
    }

    return array_filter($data);
}


//判断是否为邮箱
function isEmail($str)
{
    $pattern = "/^[-a-zA-Z0-9_]+(\.[-a-zA-Z0-9_]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,})$/i";
    preg_match($pattern, $str, $matches);
    return $matches ? true : false;
}

function UUID(){
    if (function_exists('uuid_create') === true){
        $uuid = uuid_create();
    }else{
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
        $uuid =  vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
    return $uuid;

}

function formatAvatar($avatar)
{
    $return['path'] = $avatar;
    $return['path'] = str_replace('preview/', '', $return['path']);
    $return['path'] = str_replace('avatar/', '__##__avatar/', $return['path']);
    $return['path'] = str_replace('posts/', '__##__posts/', $return['path']);
    $return['path'] = str_replace('avater/', '200x200/avater/', $return['path']);
    $return['thumb_size'] = config('app.thumb_size');
    $return['ranking']=null;
    return $return;
}


function buildAppKey()
{
    $str = getRandomStr(32,false);
    return substr($str, 0, 8) . '-'.substr($str, 8, 8). '-'.substr($str, 16, 8). '-'.substr($str, 24, 8);
}
function buildAppSecret()
{
    return strtoupper(sha1(uniqid(time())));
}

/**
 * 获得随机字符串
 * @param $len             需要的长度
 * @param $special        是否需要特殊符号
 * @return string       返回随机字符串
 */
function getRandomStr($len, $special=true){
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );

    if($special){
        $chars = array_merge($chars, array(
            "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
            "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
            "}", "<", ">", "~", "+", "=", ",", "."
        ));
    }

    $charsLen = count($chars) - 1;
    shuffle($chars);                            //打乱数组顺序
    $str = '';
    for($i=0; $i<$len; $i++){
        $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
    }
    return $str;
}


function buildAccId($member_id, $role = 1)
{
    $suffix = [
        1 => '',
        2 => "_brand",
        3 => "_shop"
    ];
    return env('APP_ENV').'_'.$member_id . $suffix[$role];
}

function buildNewsTitle($category, $title, $content)
{
    switch($category){
        case 'news':
            return html_entity_decode(htmlspecialchars_decode($title));
            break;
        case 'hotnews':
            return html_entity_decode(htmlspecialchars_decode($title));
            break;
        case 'youtube':
            return $content;
            break;
        case 'review':
            return $title;
            break;
    }
}


/**
 * --------------------------------------------------------------------------
 * 格式化 video
 * --------------------------------------------------------------------------
 * @param $video_path
 * @param int $trans
 * @param bool|false $device
 * @param bool|false $version
 * @return string
 */
function formatVideo($video_path, $trans = 1)
{
    if(!$video_path) return '';
    $host = $trans ? config('app.amazonCDN.video') : config('app.amazonCDN.video_source');
    return $host . str_replace('video 1', 'video+1', $video_path);
}

/**
 * --------------------------------------------------------------------------
 * 格式化video cover
 * --------------------------------------------------------------------------
 * @param $video_cover
 * @return mixed|string
 */
function formatVideoCover($video_cover)
{
    if(!$video_cover) return '';
    $video_cover = str_replace('videothumbnail/', '', $video_cover);
    $video_cover =   config('app.video_cover') . str_replace('video 1', 'video+1', $video_cover);
    return str_replace('videothumbnail/posts/', 'videothumbnail/__##__posts/', $video_cover);
}

/**
 * --------------------------------------------------------------------------
 * 格式化图片路径
 * --------------------------------------------------------------------------
 * @param $images
 * @return array
 */
function formatPicture($images)
{
    if(!$images) return [];
    $temp = [];
    if(!is_array($images)) $images = json_decode($images, true);
    foreach($images as $key => $val){
        $path = (strrpos($val['path'], '.gif')) ? config('app.amazonCDN.img').$val['path'] : config('app.amazonCDN.img_source').  str_replace('posts/', '__##__posts/', $val['path']);
        $data = [
            'path'  => trim($path),
            'ratio' => round($val['ratio'], 2),
            'tag'   => intval($val['tag']),
        ];

        if(isset($val['imageTags']) && !empty($val['imageTags']))
        {
            $data['imageTags'] = $val['imageTags'];
        } else {
            $data['imageTags'] = [];
        }

        $temp[] = $data;
    }
    return $temp;
}

function toArray($obj){
    return json_decode(json_encode($obj), true);
}

function decode_ascii_string($str)
{
    preg_match_all('/\&\#(\d+);/i', $str, $result);
    $index = [];
    $res = [];
    if(isset($result[0]) && count($result[0]) > 0)
    {
        foreach($result[0] as $row)
        {
            $index[] = $row;
            $res[] = ascii_decode($row);
        }

        return  str_replace($index, $res, $str);
    }

    return $str;
}

/**
 * 格式化分数输出
 * @param $score
 * @return string
 */
function shopScoreFormat($score)
{
    if(!$score)
    {
        return "10.0";
    }

    $shopScore = sprintf("%f",  $score);
    return  bcdiv($shopScore, 1, 1);

}

function mb_unserialize($str) {
    return preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';},$str);
}